package org.example.secondkill.service.impl;

import org.example.secondkill.dao.OrderDao;
import org.example.secondkill.domain.Order;
import org.example.secondkill.domain.vo.OrderVO;
import org.example.secondkill.redis.OrderKey;
import org.example.secondkill.redis.RedisService;
import org.example.secondkill.service.IOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;

@Service
public class OrderService implements IOrderService {
    private static final Logger logger = LoggerFactory.getLogger(OrderService.class);
    private static final Vector<Order> orderCache = new Vector<>();
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private RedisService redisService;

    /**
     * 生成订单
     */
    @Override
    @Transactional
    public void createOrder(long userId, long goodsId) {
        Order order = new Order();
        order.setCreateDate(new Date());
        order.setGoodsId(goodsId);
        order.setStatus(0);
        order.setUserId(userId);
        orderCache.add(order);

        // 生成秒杀订单，建立唯一索引，防止超卖
        // 将某个用户买了某个商品的信息存到 redis
        redisService.set(
                OrderKey.getOrderByUidGid,
                "" + userId + "_" + goodsId,
                order
        );
    }

    // 批量插入数据库
    @Override
    public void batchInsert() {
        long start = System.currentTimeMillis();
        List<Order> toBeInserted = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            try {
                Order tmp = orderCache.remove(0);
                toBeInserted.add(tmp);
            } catch (Exception ex) {
                break;
            }
        }
        if (toBeInserted.size() > 0) {
            orderDao.insertOrders(toBeInserted);
            logger.info("batch insert" + toBeInserted.size() + ", duration: " + (System.currentTimeMillis() - start));
        }
    }

    @Override
    public OrderVO getOrderByOrderId(long orderId) {
        return orderDao.getOrderVOByOrderId(orderId);
    }

    @Override
    public Order getOrderByUserIdAndGoodsId(long userId, long goodsId) {
        // return orderDao.getOrderByUserIdAndGoodsId(userId, goodsId);
        return redisService.get(
                OrderKey.getOrderByUidGid,
                "" + userId + "_" + goodsId,
                Order.class
        );
    }

    @Override
    public void deleteAllOrders() {
        orderDao.deleteAllOrder();
    }
}
